<template>
	<view>
		<text :style="[p1]">{{ countdown }}</text>
	</view>
</template>

<script>
export default {
	data() {
		return {
			startTime: 0,
			countdown: '',
			timer: null
		};
	},
	props: {
		timestamp: {
			type: Number,
			required: true
		},
		size: {
			type: Number,
			default: () => 26
		},
		color: {
			type: String,
			default: () => '#FFF'
		}
	},
	computed: {
		p1() {
			return {
				color: this.color,
				'font-size': this.size + 'rpx'
			};
		}
	},
	mounted() {
		this.startTime = Number(this.timestamp) * 1000 + Number(new Date().getTime());
		this.startCountdown();
	},
	beforeDestroy() {
		clearInterval(this.timer);
	},
	methods: {
		startCountdown() {
			this.updateCountdown();
			this.timer = setInterval(this.updateCountdown, 1000);
		},
		updateCountdown() {
			const now = Date.now();
			const remainingTime = this.startTime - Number(now);
			if (Number(remainingTime) <= 0) {
				this.countdown = '倒计时结束';
				this.$emit('timeOver');
				clearInterval(this.timer);
			} else {
				let seconds = Math.floor((remainingTime / 1000) % 60);
				let minutes = Math.floor((remainingTime / (1000 * 60)) % 60);
				let hours = Math.floor((remainingTime / (1000 * 60 * 60)) % 24);
				let days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
				minutes = minutes > 9 ? minutes : '0' + minutes;
				seconds = seconds > 9 ? seconds : '0' + seconds;
				if (days >= 1) return (this.countdown = `${days}天${hours}時${minutes}分${seconds}秒`);
				if (hours >= 1) return (this.countdown = `${hours}時${minutes}分${seconds}秒`);
				if (minutes >= 1) return (this.countdown = `${minutes}分${seconds}秒`);
				return (this.countdown = `${seconds}秒`);
				// this.countdown = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
			}
		}
	}
};
</script>

<style scoped lang="scss">
/* 添加样式 */
</style>
